package javabase.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient {

	private static final int size = 4096;
	private static ByteBuffer sendBuffer = ByteBuffer.allocate(size);
	private static ByteBuffer receiveBuffer = ByteBuffer.allocate(size);
	
	private static final InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(8888);
	
	
	public static void main(String[] args) throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		Selector selector = Selector.open();
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		socketChannel.connect(SERVER_ADDRESS);
		
		System.out.println(111);
		while (true) {
			selector.select();
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while (iterator.hasNext()) {
				SelectionKey key = iterator.next();
				if (key.isConnectable()) {
					System.out.println("client connecting");
					SocketChannel client = (SocketChannel) key.channel();
					if (client.isConnectionPending()) {
						client.finishConnect();
						System.out.println("clietn is connected !");
						sendBuffer.clear();
						sendBuffer.put("dek client".getBytes());
						sendBuffer.flip();
						client.write(sendBuffer);
					}
					client.register(selector, SelectionKey.OP_READ);
				} else if (key.isReadable()) {
					SocketChannel client = (SocketChannel) key.channel();
					receiveBuffer.clear();
					int count = client.read(receiveBuffer);
					if (count > 0) {
						System.out.println(new String(receiveBuffer.array(), 0, count));
						client.register(selector, SelectionKey.OP_WRITE);
					}
				} else if (key.isWritable()) {
					SocketChannel client = (SocketChannel) key.channel();
					sendBuffer.clear();
					sendBuffer.put("dek client ".getBytes());
					sendBuffer.flip();
					client.write(sendBuffer);
					System.out.println("client send data to server success");
					client.register(selector, SelectionKey.OP_READ);
				}
			}
			
		}
		
		
		
		
	}
	
}
